package com.example.pets_java.controller;

import com.example.pets_java.pojo.Comment;
import com.example.pets_java.pojo.Pet;
import com.example.pets_java.pojo.User;
import com.example.pets_java.service.CommentService;
import com.example.pets_java.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private UserService userService;


    @GetMapping("/{cId}")
    public Comment getCommentById(@PathVariable Long cId) {
        return commentService.getCommentById(cId);
    }

    @GetMapping("/list")
    public List<Comment> selectCommentList(Comment comment) {
        return commentService.selectCommentList(comment);
    }


    @PostMapping("/add")
    public void add(@RequestBody Comment comment) {

        //判断有没有父级id
        Long commentParentId = comment.getParentId();
        if(commentParentId != null){
            //有父级id,查出父级id评论
            Comment commentChirld = commentService.getCommentById(commentParentId);
            //设置评论主线id ，属于哪一个主线的评论
            if(commentChirld.getMainId() != 0){
                comment.setMainId(commentChirld.getMainId());
            }else {
                comment.setMainId(commentParentId);
            }
        }

        User user = userService.findById(Math.toIntExact(comment.getUserId()));

        comment.setCreateBy(user.getUsername());
        comment.setCreateTime(new Date());

        commentService.insertComment(comment);
    }

}
